category = {}

// - Start
category.listCat;//Khai báo var
//Print category Option for dropdown box
category.level = 0;      
category.options;
category.getOption = function(){
	if(!category.options){
		fly.ajax({
			service: '/category/getOptions',
			success: function(data){
				//$.each(data.data, function(){alert(this.itemOptionName);});
				category.options = data.data;
				return true;
			}
		});
	}		
	return true;
}
category.printCat = function(parentId){
    $.each(category.listCat, function(){
        var cat = this;
        if(cat.parentId == parentId){
            category.level ++;
            var tmp = "";
            var i = category.level;
            while(i){
                tmp += "- - ";
                i--;
            }
            
            $(' #parentId').append('<option value="'+cat.id+'">'+tmp+cat.name+'</option>');
            category.printCat(cat.id);
            category.level --;
        }
    });
    
}
//Print List NewsCat
category.printCatList = function(parentId){
    $.each(category.listCat, function(){
        var cat = this;        
            
        if(cat.parentId == parentId){
            category.level ++;
            var tmp = "";
            var i = category.level;
            while(i){
                tmp += "- - ";  
                i--;
            }
            
            if(cat.published == 1)
                cat.published = '<a onclick="category.changeStatus('+ cat.id +','+ category.level +')"><img src="'+ fly.assetsUrl +'/images/icon-enable.png" /></a>';
            else
                cat.published = '<a onclick="category.changeStatus('+ cat.id +','+ category.level +')"><img src="'+ fly.assetsUrl +'/images/icon-disable.png" /></a>';
                
            if(cat.indexPublished == 1)
                cat.indexPublished = '<a onclick="category.changeStatusIndex('+ cat.id +','+ category.level +')"><img src="'+ fly.assetsUrl +'/images/icon-enable.png" /></a>';
            else
                cat.indexPublished = '<a onclick="category.changeStatusIndex('+ cat.id +','+ category.level +')"><img src="'+ fly.assetsUrl +'/images/icon-disable.png" /></a>';
            
            $('table').append('<tr level="'+category.level+'" align="center" for="'+cat.id+'">\
                <td><input type="checkbox" for="'+cat.id+'"/></td>\
                <td><p>'+cat.id+'</p></td>\
                <td><p><img src="'+fly.uploadUrl+cat.image+'" width="50"></p></td>\
                <td style="padding-left:50px;text-align:left"><p>'+tmp+cat.name+'</p></td>\
                <td><p>'+cat.published+'</p></td>\
                <td><p>'+cat.indexPublished+'</p></td>\
                <td><p><input type="text" value="'+cat.order+'" size="5" for="'+cat.id+'"/></p></td>\
                <td><p><a onclick="category.edit('+cat.id+')">Sửa</a></p></td>\
                <td><p><a onclick="category.del('+cat.id+')">Xóa</a></p></td>\
            </tr>');
            category.printCatList(cat.id);
            category.level --;
        }
    })
}
// - End

category.list = function(){	
	category.getOption();
    main.init();	
    fly.ajax({   
        service:'/category/list',
        success: function(result){
            if(result.status){
                category.listCat = result.data;
                $('#content').html(fly.template('http://naima.vn/category/list.html', {
                    //count_data: result.data.length
                    })).show('slide', {derection: "down"}, 1000);
                
                $('#list-checkall').click(function(){
                    $('input[type=checkbox][for]').attr('checked', $('#list-checkall').is(':checked'))
                });
                $('#total-count').text(result.data.length);
                category.printCatList(0);
                category.printCat(0);
            }
            else{
                popup.msg(result.message);
            }
        }
    });
}
//Create new news category
category.create = function(){
    popup.open('popup-category-form', 'Thêm danh mục mới', fly.template('http://naima.vn/category/form.html', {
        data:null
    }), [

    {
        title:'Thêm mới', 
        fn:function(){          
			$('.optionId').val($('#optionId').val());
            fly.submitWithFile({
                id:'category-form',
                service: '/category/create',
                success: function(result){
                    if(result.data.published){
                        $('.published').attr('checked', false);
                    }
                    popup.msg(result.message);
                    popup.close('popup-category-form');
                    $('.table tr').first().after('');
                    category.printCatList(0); 
                }
            });
        }
    },
    {
        title:'Hủy bỏ',
        fn:function(){
            popup.close('popup-category-form');
        }
    }
    ]);
	//$('#popup-category-form').show('animate', {opacity: 0.5, left : '+=5', height: 'toogle'}, 5000);
	
	$('#optionId').html('');					
	if(category.getOption())
		$.each(category.options, function(){
			$('#optionId').append('<option value="'+this.id+'">'+this.itemOptionName+'</option>');
		});
    fly.ajax({
        service:'/category/list',
        success: function(result){
            category.listCat = result.data;
            category.printCat(0);
        }
    });
    category.editKeyword();
}

category.edit = function(id){
    fly.ajax({
        service: '/category/get',
        loading: false,
        data: {
            id: id
        },
        success: function(data){
            if(!data.status)
                popup.msg(data.message);
            else{
                popup.open('popup-editcat-form', 'Chỉnh sửa danh mục sản phẩm', fly.template('http://naima.vn/category/form.html', {
                    data:data.data
                }), [

                {
                    title:'Chỉnh sửa', 
                    fn:function(){
						$('.optionId').val($('#optionId').val());
                        fly.submitWithFile({
                            id:'category-form',
                            service: '/category/edit/',
                            success: function(result){
                                if(result.status){
                                    popup.msg(result.message);
                                    if(result.data.published){
                                        $('.published').attr('checked', false);
                                    }
                                    popup.close('popup-editcat-form');
                                    $('table tr').first().after('');
                                    fly.ajax({
                                        service:'/category/list',
                                        success: function(rs){
                                            if(rs.status){
                                                category.listCat = rs.data;
                                                $('#content').html(fly.template('http://naima.vn/category/list.html', {
                                                    data:null
                                                }));                                
                                                category.printCatList(0);
                                            }
                                            else{
                                                popup.msg(rs.message);
                                            }
                                        }
                                    });
                                }
                                else
                                    popup.msg(result.message);
                            }
                        });
                    }
                },
                {
                    title:'Hủy bỏ',
                    fn:function(){
                        popup.close('popup-editcat-form');
                    }
                }
                ]);
				if(category.getOption())
					$.each(category.options, function(){
						$('#optionId').append('<option value="'+this.id+'">'+this.itemOptionName+'</option>');
					});
				$('#optionId').val(data.data.optionIds.split(','));
                fly.ajax({
                    service:'/category/list',
                    loading: false,
                    success: function(res){
                        category.listCat = res.data;
                        category.printCat(0);
                        $('#parentId').val(data.data.parentId); 
                    }
                });
                category.editKeyword();
            }
        }
    });    
}

category.del = function(id){
    popup.confirm("Bạn có chắc chắn muốn xóa danh mục này?", function(){
        fly.ajax({
            service: '/category/delete/',
            data: {
                id: id
            },
            success: function(result){
                if(result.status){
                    popup.msg(result.message);
                    $('.table tr[for='+id+']').remove();
                    $.each(result.data, function(){
                        var tmp = this;
                        $('.table tr[for='+tmp.id+']').remove();
                    });
                }else
                    popup.msg(result.message);
            }
        });
    });
}

category.checkAll = function(){
    if($('#list-checkall').is(":checked"))
        $('input[type="checkbox"]').attr('checked','checked');    
    else
        $('input[type="checkbox"]').removeAttr('checked');
}
category.delAll = function(){
    var data = Array();
    var i = 0;
    $('input[type=checkbox][for]').each(function(){
        if($(this).is(':checked')){
            data[i] = parseInt($(this).attr('for'));
            i++;
        }
    });
    if(data.length <= 0){
        popup.msg("Bạn chưa chọn danh mục nào.");
        return;
    }
    popup.confirm("Bạn có chắc chắn muốn xóa danh mục đã chọn?", function(){
        fly.ajax({
            service: '/category/deleteall',
            data:{
                ids:JSON.stringify(data)
            },
            success: function(result){
                popup.msg(result.message);
                for(var i=0; i<result.data.length; i++){
                    $('.table tr[for='+result.data[i]+']').remove();
                }
            }
        });
    });
}

category.changeStatus = function(id,level){
    fly.ajax({
        service: '/category/changeStatus',
        data: {
            id:id,       
        },
        success: function(result){    
            var tmp = "";
            var i = level;
            while(i){
                tmp += "- - ";
                i--;
            }  
            $('.table tr[for='+result.data.id+']').replaceWith(fly.template('http://naima.vn/category/row.html',{
                data:result.data, 
                lvl: level,
                tmp: tmp,
            }));
        }
    });

}

category.changeStatusIndex = function(id,level){
    fly.ajax({
        service: '/category/changeStatusIndex',
        data: {
            id:id,       
        },
        success: function(result){    
            var tmp = "";
            var i = level;
            while(i){
                tmp += "- - ";
                i--;
            }  
            $('.table tr[for='+result.data.id+']').replaceWith(fly.template('http://naima.vn/category/row.html',{
                data:result.data, 
                lvl: level,
                tmp: tmp,
            }));
        }
    });

}

category.activeCheckBox = function(id){
    $('input[type="checkbox"][for="'+id+'"]').attr('checked','checked');      
}

category.saveChange = function(){
    
    var data = Array();    
    var i = 0;

    $('input[type=text][for]').each(function(){
        var cate = new Object();  
        
        cate.id = parseInt($(this).attr('for'));  
        cate.order = parseInt($('input[type="text"][for="'+$(this).attr('for')+'"]').attr('value'));
        data[i] = cate;
        i++;
    });

    popup.confirm("Bạn có chắc chắn muốn lưu các thay đổi ?", function(){
        fly.ajax({
            service: '/category/saveChange',
            method: 'post',
            data:{
                categories:JSON.stringify(data)
            },
            success: function(result){
                popup.msg('Cập nhật thay đổi thành công !');                 
            }
        });
    });

}   

category.stripHTML = function(oldString) {

   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
   
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              if(oldString.charAt(i+1)=="<")
              {
              		//dont do anything
	}
	else
	{
		inTag = false;
		i++;
	}
        }
   
        if(!inTag) newString += oldString.charAt(i);

   }

   return newString;

}

category.editKeyword = function(){
    $('#add-keyword').click(function(){
        $(this).parent('li').before('' +
            '<li class="info-keyword">' +
            '<a class="del-keyword"><img src="'+ fly.assetsUrl +'/images/icon-disable.png"></a>' +
            '<label>Từ khóa:</label><input style="width: 300px; margin-bottom: 5px;" name="CategoryForm[keyword][key][]" type="text" value="" />' +
            '<label>Link:</label><input style="width: 300px" name="CategoryForm[keyword][link][]" type="text" value="" />' +
            '</li>');
        $('.del-keyword').each(function(){
            $(this).click(function(){
                $(this).parent('.info-keyword').remove();
            })
        });
    });
    $('.del-keyword').each(function(){
        $(this).click(function(){
            $(this).parent('.info-keyword').remove();
        })
    });
}
